package cn.stylefeng.guns.modular.hxl.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hxl.entity.HxlSortTask;
import cn.stylefeng.guns.modular.hxl.entity.HxlUser;
import cn.stylefeng.guns.modular.hxl.mapper.HxlSortTaskMapper;
import cn.stylefeng.guns.modular.hxl.model.params.HxlSortTaskParam;
import cn.stylefeng.guns.modular.hxl.model.result.HxlSortTaskResult;
import  cn.stylefeng.guns.modular.hxl.service.HxlSortTaskService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 好想来-拣货任务 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-06-30
 */
@Service
public class HxlSortTaskServiceImpl extends ServiceImpl<HxlSortTaskMapper, HxlSortTask> implements HxlSortTaskService {

    @Resource
    private UserService userService;

    @Override
    public void add(HxlSortTaskParam param){
        HxlSortTask entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxlSortTaskParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxlSortTaskParam param){
        HxlSortTask oldEntity = getOldEntity(param);
        HxlSortTask newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxlSortTaskResult findBySpec(HxlSortTaskParam param){
        return null;
    }

    @Override
    public List<HxlSortTaskResult> findListBySpec(HxlSortTaskParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxlSortTaskParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 导入数据
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public ResponseData getExceldata(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        User user = userService.getcurrentUser();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return ResponseData.error("上传文件格式不正确");
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        HxlSortTask hxlSortTaskAdd = null;
        List<HxlSortTask> addList = new ArrayList<>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            hxlSortTaskAdd = new HxlSortTask();
            String  deliveryDate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(0));//配送日期
            try {
                DateUtils.parseDate(deliveryDate,"yyyy-MM-dd");
            }catch (Exception e){
                e.printStackTrace();
                return ResponseData.error("第"+(r+1) +"行第1列日期格式不正确【yyyy-MM-dd】！" );
            }

            if (ToolUtil.isNotEmpty(deliveryDate)) {
                hxlSortTaskAdd.setDeliveryDate(deliveryDate);
            } else {
                return ResponseData.error("第"+(r+1) +"行第1列[配送日期]不能为空！" );
            }

            String pickOrderNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));//单据号
            if (ToolUtil.isNotEmpty(pickOrderNumber)) {
                HxlSortTask hxlSortTask = this.baseMapper.selectById(pickOrderNumber);
                if(ToolUtil.isNotEmpty(hxlSortTask)){
                    continue;
                }
                hxlSortTaskAdd.setPickOrderNumber(pickOrderNumber);
            } else {
                return ResponseData.error("第"+(r+1) +"行第2列[单据号]不能为空！" );
            }

            String deliveryWarehouse = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(2));//发货仓库
            if (ToolUtil.isNotEmpty(deliveryWarehouse)) {
                hxlSortTaskAdd.setDeliveryWarehouse(deliveryWarehouse);
            } else {
                return ResponseData.error("第"+(r+1) +"行第3列[发货仓库]不能为空！" );
            }

            String recCustName = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(3));//收货客户
            if (ToolUtil.isNotEmpty(recCustName)) {
                hxlSortTaskAdd.setRecCustName(recCustName);
            }

            String areaName = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(4));//库区
            if (ToolUtil.isNotEmpty(areaName)) {
                hxlSortTaskAdd.setAreaName(areaName);
            }

            // 商品数
            String goodsCnt = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(5));//商品数
            if (ToolUtil.isNotEmpty(goodsCnt)) {
                try {
                    hxlSortTaskAdd.setGoodsCnt(Integer.parseInt(goodsCnt));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第6列[商品数]需要填写自然数！" );
                }
            }else{
                return ResponseData.error("第"+(r+1) +"行第6列[商品数]不能为空！" );
            }

            // 应拣数量
            String pickCnt = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(6));//应拣数量
            if (ToolUtil.isNotEmpty(pickCnt)) {
                try {
                    hxlSortTaskAdd.setPickCnt(new BigDecimal(pickCnt));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第7列[应拣数量]需要填写自然数！" );
                }
            }else{
                return ResponseData.error("第"+(r+1) +"行第7列[应拣数量]不能为空！" );
            }

            // 应拣体积(m³)
            String pickVol = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(7));//应拣体积(m³)
            if (ToolUtil.isNotEmpty(pickVol)) {
                try {
                    hxlSortTaskAdd.setPickVol(new BigDecimal(pickVol));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第7列[应拣体积]需要填写自然数！" );
                }
            }else{
                return ResponseData.error("第"+(r+1) +"行第7列[应拣体积]不能为空！" );
            }
            // 是否拆零
            String pieceFlag = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));//是否拆零
            if (ToolUtil.isNotEmpty(pieceFlag)) {
                hxlSortTaskAdd.setPieceFlag(pieceFlag);
            }else{
                hxlSortTaskAdd.setPieceFlag("否");
            }
            // 制单时间
            String prepDt = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(9));//制单时间
            if (ToolUtil.isNotEmpty(prepDt)) {
                try {
                    hxlSortTaskAdd.setPrepDt(DateUtils.parseDate(prepDt, "yyyy-MM-dd HH:mm:ss"));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第10列[制单时间]日期格式不正确【yyyy-MM-dd HH:mm:ss】！" );
                }
            } else {
                return ResponseData.error("第"+(r+1) +"行第10列[制单时间]不能为空！" );
            }
            // 分拣员
            String sorter = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(10));//分拣员
            if (ToolUtil.isNotEmpty(sorter)) {
                hxlSortTaskAdd.setSorter(sorter);
            } else {
                return ResponseData.error("第"+(r+1) +"行第11列[分拣员]不能为空！" );
            }
            // 领取时间
            String receiveTime = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(11));//领取时间
            if (ToolUtil.isNotEmpty(receiveTime)) {
                try {
                    hxlSortTaskAdd.setReceiveTime(DateUtils.parseDate(receiveTime, "yyyy-MM-dd HH:mm:ss"));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第12列[领取时间]日期格式不正确【yyyy-MM-dd hh:mm:ss】！" );
                }
            } else {
                return ResponseData.error("第"+(r+1) +"行第12列[领取时间]不能为空！" );
            }
            // 分拣完成时间
            String sortCompleteTime = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(12));//分拣完成时间
            if (ToolUtil.isNotEmpty(sortCompleteTime)) {
                try {
                    hxlSortTaskAdd.setSortCompleteTime(DateUtils.parseDate(sortCompleteTime, "yyyy-MM-dd HH:mm:ss"));
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseData.error("第"+(r+1) +"行第13列[分拣完成时间]日期格式不正确【yyyy-MM-dd hh:mm:ss】！" );
                }
            } else {
                return ResponseData.error("第"+(r+1) +"行第13列[分拣完成时间]不能为空！" );
            }
            // AGV任务
            String agvFlag = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(13));//AGV任务
            if (ToolUtil.isNotEmpty(agvFlag)) {
                hxlSortTaskAdd.setAgvFlag(agvFlag);
            }else{
                hxlSortTaskAdd.setAgvFlag("否");
            }

            hxlSortTaskAdd.setCreateUser(user.getUserId());
            hxlSortTaskAdd.setCreateTime(new Date());
            addList.add(hxlSortTaskAdd);
        }

        if(addList.size() > 0){
            this.saveBatch(addList);
        }
        return ResponseData.success();
    }

    private Serializable getKey(HxlSortTaskParam param){
        return param.getPickOrderNumber();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxlSortTask getOldEntity(HxlSortTaskParam param) {
        return this.getById(getKey(param));
    }

    private HxlSortTask getEntity(HxlSortTaskParam param) {
        HxlSortTask entity = new HxlSortTask();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
